<?php

namespace App\Models;


use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use DB;
/**
 * Class AdminUser
 * @property string id
 * @property string name 昵称
 * @property string email email
 * @property string password 密码
 */
class AdminUser extends ApplicationModel implements AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;
    protected $fillable = [
        'name',
        'email',
        'password',
        'is_promote',
    ];

    public function roles()
    {
        return $this->belongsToMany(AdminRole::class, 'admin_assigned_roles', 'admin_user_id', 'admin_role_id');
    }

    public function permissions()
    {
        $roles = \DB::table('admin_users')
            ->select("admin_assigned_roles.admin_role_id as admin_role_id")
            ->leftJoin('admin_assigned_roles', 'admin_users.id', '=', 'admin_assigned_roles.admin_user_id')
            ->where("admin_assigned_roles.admin_user_id", "=", $this->id)
            ->orderBy("admin_assigned_roles.id", "desc")
            ->get();
        $permissions_ids = [];
        foreach ($roles as $role) {
            $permissionroles = \DB::table("admin_permission_roles")
                ->select("admin_permissions.link as url")
                ->join('admin_permissions', 'admin_permissions.id', '=', 'admin_permission_roles.admin_permission_id')
                ->where("admin_permission_roles.admin_role_id", $role->admin_role_id)->get();
            foreach ($permissionroles as $permission) {
                $permissions_ids[] = $permission->url;
            }
        }
        return $permissions_ids;
    }
}
